#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试局部变量名与方法名冲突的情况

当局部变量名与方法名相同时（如 index: int = words.index("banana")），
符号查找应该能正确区分：
- 左边的 index 是局部变量
- 右边的 index 是 list 的方法
"""

from tests.pytests.helpers.codegen_helpers import compile_source


def test_local_variable_shadows_method_name():
    """测试局部变量名遮盖方法名的情况"""
    source = """
def test_index():
    words = ["apple", "banana"]
    index: int = words.index("banana")
    return index
"""

    hpp, cpp = compile_source(source)

    # 应该能成功编译
    assert "mcpy::list_index" in cpp or "list_index" in cpp, "应该生成 list_index 调用"
    assert "index =" in cpp, "应该定义 index 变量"
    assert "return index" in cpp, "应该能使用 index 变量"


def test_multiple_functions_with_same_local_variable_name():
    """测试多个函数中使用相同的局部变量名（与方法名冲突）"""
    source = """
def test_int_list():
    numbers = [10, 20, 30]
    result: int = numbers.index(20)
    return result

def test_str_list():
    words = ["apple", "banana"]
    index: int = words.index("banana")
    return index
"""

    hpp, cpp = compile_source(source)

    # 两个函数都应该能成功编译
    assert "mcpy::list_index" in cpp or "list_index" in cpp, "应该生成 list_index 调用"


def test_local_variable_with_append_call():
    """测试局部变量名为 append 时的情况"""
    source = """
def test_append():
    numbers = [1, 2, 3]
    numbers.append(4)
    append: int = 5  # 局部变量名为 append
    return append
"""

    hpp, cpp = compile_source(source)

    # 应该能成功编译
    assert "append(4)" in cpp or "push_back(4)" in cpp, "应该生成 append 调用"
    assert "append =" in cpp, "应该定义 append 变量"
    assert "return append" in cpp, "应该能使用 append 变量"


def test_local_variable_shadows_before_method_call():
    """测试赋值语句中，左边的局部变量不应该影响右边的方法调用"""
    source = """
def test():
    words = ["apple", "banana", "cherry"]
    words.append("orange")
    words.insert(1, "grape")
    
    # 关键：赋值语句的左边定义了 index 变量
    # 右边应该仍然能找到 words.index 方法
    index: int = words.index("banana")
    expected: int = 2
    
    return index == expected
"""

    hpp, cpp = compile_source(source)

    # 应该能成功编译
    assert "append" in cpp or "push_back" in cpp, "应该生成 append 调用"
    assert "insert" in cpp, "应该生成 insert 调用"
    assert "mcpy::list_index" in cpp or "list_index" in cpp, "应该生成 list_index 调用"
    assert "index =" in cpp, "应该定义 index 变量"


def test_method_name_conflict_with_multiple_types():
    """测试不同类型的方法调用（整数列表和字符串列表）"""
    source = """
def test_int_index():
    numbers = [10, 20, 30, 20, 40]
    result: int = numbers.index(20)
    return result

def test_str_index():
    words = ["apple", "banana"]
    words.append("orange")
    words.insert(1, "grape")
    
    expected = ["apple", "grape", "banana", "orange"]
    
    # 测试查找
    index: int = words.index("banana")
    expected_index: int = 2
    
    return index == expected_index
"""

    hpp, cpp = compile_source(source)

    # 应该能成功编译
    assert (
        cpp.count("mcpy::list_index") >= 2 or cpp.count("list_index") >= 2
    ), "应该至少有两次 list_index 调用"
